import axios from 'axios'
import store from '../store'
import router from '../router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 默认请求的基础地址
const request = axios.create({
  baseURL: 'https://conduit.productionready.io',
  // timeout: 5000
})

request.interceptors.request.use(function (config) {
  NProgress.start()
  store.dispatch('clearErrors')
  
  if (config.headers.needToken) {
    const token = sessionStorage.getItem('token_key')
    if (token) {
      config.headers.Authorization = 'Token ' + token
    }
  }
  return config
}, function (error) {
  return Promise.reject(error);
})


// 响应拦截器，直接输出数据信息，并且直接在拦截器中实现请求失败
request.interceptors.response.use(function (response) {
  NProgress.done()
  return response.data;
}, function (error) {
  if (error.response.status == 401 || error.response.status == 402) {
    // 调用退出登录的方法
    store.dispatch('resetUser')
    if (router.currentRoute.path !== '/login') {
      alert('请登录后再访问')
      router.push('/login')
    }
  }else if(error.response.status == 422){
    const err = error.response.data.errors
    store.dispatch('errors', err)
  }else if(error.response.status === 404){
    console.log('请求资源不存在')
  }else{
    console.dir(error)
    alert(error.response.data.errors)
  }
  console.dir(error)
  NProgress.done()
  return new Promise(() => { })
})

export default request